package dev.spb3.service;

import dev.spb3.common.exception.FileStorageException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

/**
 * 文件存储服务
 */
@Service
public class FileStorageService {
    private final Path fileStorageLocation;
    // 构造函数，初始化文件存储目录
    public FileStorageService(@Value("${file.upload-dir}") String uploadDir) {
        // 将配置中的上传目录路径转换为绝对路径并规范化
        this.fileStorageLocation = Paths.get(uploadDir).toAbsolutePath().normalize();
        try {
            // 确保文件存储目录存在
            Files.createDirectories(this.fileStorageLocation);
        } catch (Exception e) {
            throw new FileStorageException("创建文件存储目录失败：" + e.getMessage());
        }
    }

    /**
     * 存储文件
     * @param file
     * @return
     */
    public String storeFile(MultipartFile file) {
        // 清洁文件名
        String fileName = StringUtils.cleanPath(file.getOriginalFilename());
        try {
            // 检查文件名是否包含 ..
            if (fileName.contains("..")) {
                throw new FileStorageException("文件名非法：" + fileName);
            }
            // 将文件复制到目标位置
            Path targetLocation = this.fileStorageLocation.resolve(fileName);
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
            return fileName;
        } catch (IOException ex) {
            throw new FileStorageException("文件存储失败：" + fileName, ex);
        }
    }
}
